package com.zdb.service.impl;


import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zdb.mapper.PerssionMapper;
import com.zdb.mapper.UserMapper;
import com.zdb.pojo.LoginUser;
import com.zdb.pojo.User;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class UserDetailServiceImpl implements UserDetailsService {
    private static final Logger log = LoggerFactory.getLogger(UserDetailServiceImpl.class);
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private PerssionMapper perssionMapper;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        if (StrUtil.isNotEmpty(username)){
            User user = userMapper.selectOne(new LambdaQueryWrapper<User>
                    ().eq(User::getUsername, username));
            if (ObjectUtil.isNotNull( user)&&ObjectUtil.isNotEmpty(user.getId())){
                List<String> strings = perssionMapper.selectById(user.getId());
                LoginUser loginUser = new LoginUser();
                BeanUtils.copyProperties(user, loginUser);
                loginUser.setPermissions( strings);
                return loginUser;
            }
        }
        return null;
    }
}
